package com.xxwy.ddu.cms.authonrize.impl;

import com.xxwy.ddu.cms.authonrize.service.IAccessService;
import com.xxwy.ddu.security.code.authonrize.RbacService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author xxwy
 * on 2018/9/3 0003
 */
@Component("rbacService")
@Slf4j
public class RbacServiceImpl implements RbacService {

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Autowired
    IAccessService iAccessService;

    @Override
    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
        Object principal = authentication.getPrincipal();
        boolean hasPermission = false;
        // 有可能 principal 是一个Anonymous
        // 所以只要是一个UserDetails那么就能标识是经过了我们自己的数据库查询的
        // 当前需要先配置UserDetailsServices
        if (principal instanceof UserDetails) {
            //判断是不是主页，是就放行啊。。
            if(antPathMatcher.match("/index", request.getRequestURI())){
                hasPermission = true;
            }else {
                String username = ((UserDetails) principal).getUsername();
                //读取用户所拥有权限的所有URL
                List<String> allUrls = iAccessService.getUserUrls(username);
                if (allUrls != null) {
                    for (String url : allUrls) {
                        if (antPathMatcher.match(url, request.getRequestURI())) {
                            hasPermission = true;
                            log.info("用户拥有权限");
                            break;
                        }
                    }
                }
            }
        }
        return hasPermission;
    }
}
